<dom-module id="grid-crud-demos">
  <template>
    <style include="vaadin-component-demo-shared-styles">
      :host {
        display: block;
      }
    </style>

    <style>
      vaadin-grid {
        text-transform: none;
      }
    </style>


    <h3>Create, Read, Update and Delete</h3>
    <p>
      Grid renderers and JavaScript functions can be used to implement inline editing.
    </p>
    <p>
      <b>Note:</b> Remember to call <code>grid.clearCache()</code> to show updated data.
    </p>
    <vaadin-demo-snippet id="grid-crud-demos-crud" when-defined="vaadin-grid">
      <template preserve-content>
        <style>
          vaadin-grid vaadin-text-field {
            width: 100%;
          }

          vaadin-grid vaadin-button {
            margin-left: 5px;
          }
        </style>
        <x-array-data-provider></x-array-data-provider>

        <div style="margin-bottom: 20px;">
          <vaadin-text-field id="firstname" header="First name"></vaadin-text-field>
          <vaadin-text-field id="lastname" header="Last name"></vaadin-text-field>
          <vaadin-button id="add-btn">Add</vaadin-button>
        </div>

        <vaadin-grid theme="compact">
          <vaadin-grid-column name="First name" resizable></vaadin-grid-column>
          <vaadin-grid-column name="Last name" resizable></vaadin-grid-column>
          <vaadin-grid-column name="E-Mail" width="12em" resizable></vaadin-grid-column>
          <vaadin-grid-column width="14em"></vaadin-grid-column>
        </vaadin-grid>
        <script>
          window.addDemoReadyListener('#grid-crud-demos-crud', function(document) {
            const grid = document.querySelector('vaadin-grid');
            const firstname = document.querySelector('#firstname');
            const lastname = document.querySelector('#lastname');

            const addBtn = document.querySelector('#add-btn');

            addBtn.addEventListener('click', function() {
              if (firstname.value && lastname.value) {
                grid.items.unshift({name: {first: firstname.value, last: lastname.value}});
                grid.clearCache();
                firstname.value = lastname.value = '';
              } else {
                alert('First name and Last name required');
              }
            });

            const columns = document.querySelectorAll('vaadin-grid-column');

            columns[0].headerRenderer =
            columns[1].headerRenderer =
            columns[2].headerRenderer = function(root, column) {
              root.textContent = column.getAttribute('name');
            };

            columns[0].renderer =
            columns[1].renderer = function(root, column, model) {
              let textField = root.firstElementChild;
              if (!textField) {
                textField = window.document.createElement('vaadin-text-field');
                root.appendChild(textField);
              }
              const property = column == columns[0] ? 'first' : 'last';
              // set an id so as we can find it in the dom when clicking on action buttons.
              textField.id = property + model.index;
              textField.value = model.item.name[property];
              textField.readonly = true;
              textField.setAttribute('focus-target', true);
            };

            columns[2].renderer = function(root, column, model) {
              root.textContent = model.item.name.first + '.' + model.item.name.last + '@example.com';
            };

            columns[3].renderer = function(root, column, model) {
              let wrapper = root.firstElementChild;
              if (!wrapper) {
                root.innerHTML =
                  '<div style="text-align: right">' +
                    '<vaadin-button aria-label="Edit" theme="icon" focus-target>' +
                      '<iron-icon icon="lumo:edit"></iron-icon>' +
                    '</vaadin-button>' +
                    '<vaadin-button aria-label="Delete" theme="icon error">' +
                      '<iron-icon icon="lumo:cross"></iron-icon>' +
                    '</vaadin-button>' +
                    '<vaadin-button aria-label="Save" theme="primary" focus-target hidden>Save</vaadin-button>' +
                    '<vaadin-button aria-label="Cancel" hidden>Cancel</vaadin-button>' +
                  '</div>';
                wrapper = root.firstElementChild;

                const buttons = wrapper.querySelectorAll('vaadin-button');
                // EDIT
                buttons[0].addEventListener('click', function() {
                  updateTextFieldsVisibility(wrapper.idx, true);
                  updateButtonsVisibility(buttons, wrapper.idx, true);
                  grid.querySelector('#first' + wrapper.idx).focus();
                });
                // DELETE
                buttons[1].addEventListener('click', function(event) {
                  grid.items.splice(wrapper.idx, 1);
                  grid.clearCache();
                });
                // SAVE
                buttons[2].addEventListener('click', function() {
                  grid.items[wrapper.idx].name.first = grid.querySelector('#first' + wrapper.idx).value;
                  grid.items[wrapper.idx].name.last = grid.querySelector('#last' + wrapper.idx).value;
                  buttons[3].click();
                });
                // CANCEL
                buttons[3].addEventListener('click', function(event) {
                  updateTextFieldsVisibility(wrapper.idx, false);
                  updateButtonsVisibility(buttons, wrapper.idx, false);
                  grid.clearCache();
                  buttons[0].focus();
                });
              }

              // We reuse rendered content, but maintain a property with the index for actions
              wrapper.idx = model.index;
            };

            function updateTextFieldsVisibility(index, editing) {
              grid.querySelector('#first' + index).readonly = !editing;
              grid.querySelector('#last' + index).readonly = !editing;
            }

            function updateButtonsVisibility(buttons, index, editing) {
              buttons[0].hidden = buttons[1].hidden = editing;
              buttons[2].hidden = buttons[3].hidden = !editing;
            }

            const dataProvider = document.querySelector('x-array-data-provider');
            dataProvider.size = 200;
            grid.items = dataProvider.items;
          });
        </script>
      </template>
    </vaadin-demo-snippet>

  </template>
  <script>
    class GridCrudDemos extends DemoReadyEventEmitter(GridDemo(Polymer.Element)) {
      static get is() {
        return 'grid-crud-demos';
      }
    }
    customElements.define(GridCrudDemos.is, GridCrudDemos);
  </script>
</dom-module>
